package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * @Desceription: 获取图形验证码
     * @Return: com.atguigu.lease.web.admin.vo.login.CaptchaVo
     * @Author: yangchengbao
     * @Date: 2024-12-13 15:12:36
     */
    @Override
    public CaptchaVo getCaptcha() {
        // 生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");

        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.MINUTES);

        String base64 = specCaptcha.toBase64();
        CaptchaVo captchaVo = new CaptchaVo(base64, key);
        return captchaVo;
    }

    /**
     * @param loginVo
     * @Desceription: 登录
     * @Return: java.lang.String
     * @Author: yangchengbao
     * @Date: 2024-12-13 15:12:28
     */
    @Override
    public String login(LoginVo loginVo) {
        String captchaCode = loginVo.getCaptchaCode();
        // 验证码是否为空
        if (captchaCode == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        // 验证码是否过期
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        String lowerCase = code.toLowerCase();
        // 验证码是否正确
        if (!lowerCase.equals(captchaCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        String username = loginVo.getUsername();
        SystemUser systemUser = systemUserMapper.selectOneByUsername(username);
        // 校验用户名是否存在
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        BaseStatus status = systemUser.getStatus();
        // 校验用户是否禁用
        if (status.equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        String password_str = loginVo.getPassword();
        String password = DigestUtils.md5Hex(password_str);
        // 校验密码是否正确
        if (!systemUser.getPassword().equals(password)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        String token = JwtUtil.createToken(systemUser.getId(), username);


        return token;
    }

    /**
     * @param userId
     * @Desceription: 获取登录用户个人信息
     * @Return: com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo
     * @Author: yangchengbao
     * @Date: 2025-01-04 12:01:24
     */
    @Override
    public SystemUserInfoVo getLoginUserInfoByUserId(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo=new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
